<template>
  <div class="app-container">
    <el-container>
      <el-header>
        <el-form :model="form" ref="form" :inline="true" :rules="rules" v-show="showSearch" label-width="80px">
          <el-row>
            <el-col>
              <el-form-item>
                <el-button type="primary" @click="handleQuery" v-hasPermi="['dms:non_drug_model:add']">新建模板</el-button>
                <el-button type="danger" @click="resetQuery">取消</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="模版名字" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入模版名字"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="模版简介" prop="aim">
                <el-input
                  v-model="form.aim"
                  placeholder="请输入模版简介"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="模版范围" prop="scope">
                <el-select v-model="form.scope" placeholder="请选择模版范围" clearable size="small">
                  <el-option
                    v-for="dict in scopeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="parseInt(dict.dictValue)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-show="updShow">
            <el-col>
              <el-form-item label="创建时间" prop="aim">
                <el-input
                  v-model="form.createTime"
                  clearable
                  size="small"
                  :disabled="true"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="模板编号" prop="aim">
                <el-input
                  v-model="form.code"
                  clearable
                  size="small"
                  :disabled="true"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-header>
      <!--药品详情-->
      <el-main>
        <el-row style="margin-top: 100px">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >编辑项目</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="drug_modelList">
          <el-table-column label="药品名" align="center" prop="name" />
          <el-table-column label="药品规格" align="center" prop="format" />
          <el-table-column label="药品单价" align="center" prop="price" />
          <el-table-column label="药品数量" align="center" prop="num" />
          <el-table-column label="总价" align="center" prop="total" >
            <template slot-scope="scope">{{scope.row.price*scope.row.num | rounding}}</template>
          </el-table-column>
          <el-table-column label="拼音码" align="center" prop="mnemonicCode" />
          <el-table-column label="使用建议" align="center" prop="medicalAdvice" />
          <el-table-column label="频次" align="center" prop="frequency" :formatter="frequencyFormat" />
          <el-table-column label="天数" align="center" prop="days" />
          <el-table-column label="用量" align="center" prop="usageNum" />
          <el-table-column label="单位" align="center" prop="usageNumUnit" :formatter="usageNumUnitFormat" />
        </el-table>
      </el-main>
    </el-container>

    <!-- 添加或修改药品模版管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1800px" style="height: 900px;" append-to-body>
      <el-container>
        <!--药品查询-->
        <el-aside width="360px" style="background-color: white;height: 500px">
          <el-form ref="queryForm" :model="queryParams" label-width="80px">
            <el-row style="background-color: azure;height: 40px" >
              <el-col :span="36">
                <el-form-item label="药品目录" prop="name">
                  <el-input v-model="queryParams.name" placeholder="药品名字" @keyup.enter.native="queryDrug"/>
                </el-form-item>
              </el-col>
              <el-col :span="1.0">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="queryDrug"></el-button>
              </el-col>
            </el-row>
          </el-form>
          <el-table :data="getDrupList" style="height:350px;width:360px;overflow: auto;" @row-click="drugClick">
            <el-table-column label="药品名称" align="center" prop="name" />
            <el-table-column label="价格(元)" align="center" prop="price" />
          </el-table>
          <pagination
            small
            :total="total"
            layout="prev, pager, next"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getDrugList"
          />
        </el-aside>
        <!--药品详情-->
        <el-main>
          <el-row>
            <el-col>
              <el-tag style="margin-right: 10px">项目金额总价:</el-tag>
              <el-tag type="danger">{{ totalMoney | rounding}} 元</el-tag>
            </el-col>
          </el-row>
          <el-table :data="drugInfoList">
            <el-table-column align="center" class-name="small-padding fixed-width" width="50px">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="drugDelete(scope.$index,drugInfoList)"
                >删除</el-button>
              </template>
            </el-table-column>
            <el-table-column label="药品名" align="center" prop="name" />
            <el-table-column label="规格" align="center" prop="format" />
            <el-table-column label="单价" align="center" prop="price" width="60px"/>
            <el-table-column label="数量" align="center" prop="num">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.num" @change="handleChange" controls-position="right" size="small" style="width: 100px"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="剂型" align="center" prop="dosageName"/>
            <el-table-column label="使用建议" align="center" prop="medicalAdvice" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.medicalAdvice" />
              </template>
            </el-table-column>
            <el-table-column label="频次" align="center" prop="frequency" >
              <template slot-scope="scope">
                <el-select placeholder="请选择频次" v-model="scope.row.frequency">
                  <el-option
                    v-for="dict in frequencyOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="parseInt(dict.dictValue)"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="天数" align="center" prop="days" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.days" />
              </template>
            </el-table-column>
            <el-table-column label="用量" align="center" prop="usageNum" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.usageNum" />
              </template>
            </el-table-column>
            <el-table-column label="单位" align="center" prop="usageNumUnit">
              <template slot-scope="scope">
                <el-select placeholder="请选择单位" v-model="scope.row.usageNumUnit" >
                  <el-option
                    v-for="dict in usageNumUnitOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="parseInt(dict.dictValue)"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDrug_model, addDrug_model, updateDrug_model } from "@/api/dms/drug_model";
import { listDrug } from "@/api/dms/drug";
export default {
  name: "Edit_drug_model",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 创建时间，模板编码的显示隐藏
      updShow:false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药品模版表格数据详情
      drug_modelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 模版范围字典
      scopeOptions: [],
      // 频次字典
      frequencyOptions: [],
      // 单位字典
      usageNumUnitOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模板名称不能为空！", trigger: "blur" }
        ],
        aim: [
          { required: true, message: "模板简介不能为空！", trigger: "blur" }
        ],
        scope: [
          { required: true, message: "范围不能为空！", trigger: "change" }
        ],
      },
      //左边药品表格
      getDrupList:[],
      //右边药品详情数据
      drugInfoList:[],
      //项目总金额
      totalMoney:0,
    };
  },
  /** 过滤总价，只要小数点后两位*/
  filters: {
    rounding (value) {
      return value.toFixed(2);
    }
  },
  created() {
    this.getList();
    this.getDicts("dms_model_scoe").then(response => {
      this.scopeOptions = response.data;
    });
    this.getDicts("dms_drug_frequency").then(response => {
      this.frequencyOptions = response.data;
    });
    this.getDicts("dms_drug_unit").then(response => {
      this.usageNumUnitOptions = response.data;
    });
  },
  methods: {
    /** 查询药品模版详情列表 */
    getList() {
      if(this.$route.query.id != null){
        this.loading = true;
        this.updShow = true;
        getDrug_model(this.$route.query.id).then(response => {
          this.form = response.data;
          this.drug_modelList = response.data.dmsMedicineModelItems.map((item,index) => {
            return {...item,...response.data.dmsDrugs[index]};
          });
          console.log(this.drug_modelList);
          this.loading = false;
        });
      }
    },
    /** 编辑项目按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加药品";
      this.queryParams.name=null;
      this.getDrugList();
      this.drugInfoList = [];
      for(let i = 0; i < this.drug_modelList.length; i++){
        this.drugInfoList.push(this.drug_modelList[i]);
      }
      console.log("编辑->"+this.drugInfoList);
      this.totalPrice();
    },
    //数量change事件
    handleChange(){
      this.totalPrice();
    },
    //计算总价
    totalPrice(){
      this.totalMoney = 0;
      for(let i= 0;i<this.drugInfoList.length;i++){
        this.totalMoney += this.drugInfoList[i].num*this.drugInfoList[i].price;
      }
    },
    //药品搜索
    queryDrug(){
      this.queryParams.pageNum = 1;
      this.getDrugList();
    },
    /** 查询药品详情 方法*/
    getDrugList(){
      this.queryParams.typeId = 102;
      listDrug(this.queryParams).then(response => {
        this.getDrupList = response.rows;
        this.total = response.total;
      });
    },
    /** 药品行点击事件*/
    drugClick(row){
      for(let i = 0; i<this.drugInfoList.length;i++){
        if(this.drugInfoList[i].id == row.id){
          this.drugInfoList[i].num = this.drugInfoList[i].num+1;
          this.totalPrice();//计算总金额
          return true;
        }
      }
      this.drugInfoList.push({id:row.id,name:row.name,format:row.format,price:row.price,mnemonicCode:row.mnemonicCode,dosageName:row.dosageName,num:1});
      this.totalPrice();//计算总金额
    },
    /** 添加药品弹框的确定按钮 */
    submitForm() {
      this.drug_modelList = this.drugInfoList;
      this.open = false;
    },
    /** 删除该行药品信息按钮操作 */
    drugDelete(index,row){
      row.splice(index,1);
      this.totalPrice();//计算总金额
    },
    // 弹框取消按钮
    cancel() {
      this.open = false;
    },
    /** 新建项目按钮操作 */
    handleQuery() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.type = 1;//成药模板
          this.form.dmsDrugs = this.drug_modelList;//需要药品id
          this.form.dmsMedicineModelItems = this.drug_modelList;
          if (this.form.id != null) {
            updateDrug_model(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push("/model/drug_model");
              }
            });
          } else {
            addDrug_model(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.push("/model/drug_model");
              }
            });
          }
        }
      });
    },
    /** 取消回退按钮操作 */
    resetQuery() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push("/model/drug_model");
    },
    // 模版范围字典翻译
    scopeFormat(row, column) {
      return this.selectDictLabel(this.scopeOptions, row.scope);
    },
    // 频次字典翻译
    frequencyFormat(row, column) {
      return this.selectDictLabel(this.frequencyOptions, row.frequency);
    },
    // 单位字典翻译
    usageNumUnitFormat(row, column) {
      return this.selectDictLabel(this.usageNumUnitOptions, row.usageNumUnit);
    },

  }
};
</script>
